package com.shujia.day16.udp2;



import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Receiver {

    public static void main(String[] args) throws IOException {
        /*
            实现一个不断接收数据的功能
         */

        DatagramSocket socket = new DatagramSocket(12346);

        byte[] bytes = new byte[1024];

        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

        while (true){
            // 在While循环中不断接收传入过来的数据
           socket.receive(datagramPacket);

            byte[] data = datagramPacket.getData();
            int length = datagramPacket.getLength();

            String dataStr = new String(data, 0, length);

            // 获取发送方的IP以及对应的端口

            InetAddress address = datagramPacket.getAddress();
            int port = datagramPacket.getPort();
            String ip = address.getHostAddress();
            String hostName = address.getHostName();

            System.out.println("接收到用户:"+hostName+" IP:"+ip+" Port:"+port+" 发送的数据数据："+dataStr);

        }
    }
}
